package com.blog.admin.utils;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisUtils implements ApplicationContextAware{
	private static ApplicationContext applicationContext = null;

    private static JedisPool jedisPool = null;

    private static volatile Jedis jedis = null;
	
    public static Jedis getJedis(){
        if (jedis ==null){
            synchronized (Jedis.class){
                if (jedis ==null){
                    jedis = getJedisPool().getResource();
                }
            }
        }
        return jedis;
    }

    public static JedisPool getJedisPool(){
        if (jedisPool ==null){
            synchronized (JedisPool.class){
                if (jedisPool==null){
                    jedisPool = applicationContext.getBean(JedisPool.class);
                }
            }
        }
        return jedisPool;
    }

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if(RedisUtils.applicationContext == null){
			RedisUtils.applicationContext  = applicationContext; //初始化 spring applicationContext
        }
	}
	
	public static void name() {
		//System.out.println(getJedis().get("a"));
	}

	/**
	 * 保存登录的用户菜单权限
	 * @param id
	 * @param map
	 */
	public static void saveUserMenus(Integer id, String listPermissions) {
		getJedis().hset(CacheKeys.USER_PERMISSIONS, id.toString(), listPermissions);
	}

	
	public static String getUserMenus(Integer id) {
		String menus = getJedis().hget(CacheKeys.USER_PERMISSIONS, id.toString());
		return menus;
	}
}
